package main

import (
	"context"
	"encoding/json"
	"github.com/olivere/elastic/v7"
	"time"
)

// NotificationFrequencyControl 告警通知频率控制
func NotificationFrequencyControl() {
	log.Info("执行推送频率限制")
	// 推送频率
	alertPushFrequency, err := GetConfig("default", "alertPushFrequency")
	if err != nil {
		log.Warnf("未找到推送频率设置,将使用默认参数 1h")
		alertPushFrequency = "1h"
	}
	client, _ := EsConnect()
	indexName, err := GetConfig("default", "indexName")
	if err != nil {
		log.Fatalf("索引获取失败: %v", err)
	}

	notificationFrequencyDuration, err := time.ParseDuration(alertPushFrequency)
	if err != nil {
		log.Fatalf("无法解析参数notificationFrequencyDuration: %v", err)
	}

	// 查询Elasticsearch
	searchService := client.Search().
		Index(indexName).
		Query(elastic.NewTermQuery("status", true))

	searchResult, err := searchService.Do(context.Background())
	if err != nil {
		log.Fatalf("执行搜索查询时出错: %s", err)
	}

	for _, item := range searchResult.Hits.Hits {
		var alertData AlertData
		err := json.Unmarshal(item.Source, &alertData)
		if err != nil {
			log.Errorf("分解文档出错: %s", err)
			continue
		}
		currentTime := time.Now()

		//将lastNotice字符串解析为time.Time
		lastNotice, err := time.Parse(time.RFC3339, alertData.LastNotice)
		if err != nil {
			log.Errorf("解析last_notice时间失败: %s", err)
			continue
		}

		timeDiff := currentTime.Sub(lastNotice)
		if timeDiff > notificationFrequencyDuration {
			MsgDestinationSelection(alertData)

			// 更新 last_notice 为当前时间
			updateScript := elastic.NewScript(`
            ctx._source.last_notice = params.new_last_notice
        `).Params(map[string]interface{}{
				"new_last_notice": currentTime.Format(time.RFC3339),
			})

			_, err := client.Update().
				Index(indexName).
				Id(item.Id).
				Script(updateScript).
				Do(context.Background())

			if err != nil {
				log.Errorf("更新索引出错: %s", err)
			} else {
				log.Infof("更新通知时间成功: %s", currentTime)
			}
		}
	}
}

// MsgDestinationSelection 将告警推送至指定平台
func MsgDestinationSelection(alertData AlertData) {
	log.Infof("%s 触发告警", alertData.Alert)
	// 告警内容格式：标题\n告警项:\n告警规则:\当前值:\n描述
	pushDest, err := GetConfig("default", "pushDest")
	if err != nil {
		log.Fatal("未配置推送平台!")
	}
	switch pushDest {
	case "DingDing":
		log.Debug("已推送到DingDing")
		DingDing(alertData)
	case "FeiShu":
		log.Debug("已推送到FeiShu")
		FeiShu("")
	case "email":
		log.Debug("email")
		Email("")
	}
}
